package com.kangfuqiang.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;


public class LruMap<K, V>{
	private static final long serialVersionUID = 1L;
	private HashMap<K,Long> valueTimeMap = new HashMap<K,Long>();
	private HashMap<K,V> valueMap = new HashMap<K,V>();
	private LinkedList<K> keyList = new LinkedList<K>();
	
	private int cacheTime;
	
	/**
	 * @param cacheTime 缓存时间（秒）
	 */
	public LruMap(int cacheTime) {
		super();
		this.cacheTime = cacheTime;
	}

	public synchronized void put(K key,V value)
	{
		//检查是否有过期的key
		processOldKey();
		if(false == valueMap.containsKey(key)){
			valueTimeMap.put(key,System.currentTimeMillis());
			keyList.add(key);
		}
		valueMap.put(key, value);
	}
	
	private void processOldKey() {
		Iterator<K> iter = keyList.iterator();
		while(iter.hasNext()){
			K key = iter.next();
			V value = get(key);
			if(null == value){
				iter.remove();
			}else{
				break;
			}
		}
		
	}

	public synchronized V get(K key)
	{
		V value = valueMap.get(key);
		if(null == value){
			return null;
		}
		Long t = valueTimeMap.get(key);
		if((t+cacheTime*1000) > System.currentTimeMillis()){
			return value;
		}else{
			valueTimeMap.remove(key);
			valueMap.remove(key);
			return null;
		}
	}
}
